package org.dromara.demo.controller;

import java.io.IOException;
import java.util.List;

import cn.dev33.satoken.annotation.SaMode;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.demo.service.IJsSuiteService;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.demo.domain.vo.JsExampleVo;
import org.dromara.demo.domain.bo.JsExampleBo;
import org.dromara.demo.service.IJsExampleService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 测试用例
 *
 * @author zhu
 * @date 2024-12-26
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/demo/example")
public class JsExampleController extends BaseController {

    private final IJsExampleService jsExampleService;

    private final IJsSuiteService jsExecuteService;

    /**
     * 查询测试用例列表
     */
    @SaCheckPermission("demo:example:list")
    @GetMapping("/list")
    public TableDataInfo<JsExampleVo> list(JsExampleBo bo, PageQuery pageQuery) {
        return jsExampleService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询测试用例列表
     */
    @SaCheckPermission(value = {"demo:example:list", "demo:example:query"}, mode = SaMode.OR)
    @GetMapping("/execute")
    public R<Void> execute(JsExampleBo bo) throws IOException {
//        DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
//        desiredCapabilities.setCapability("platformName", "Android");
//        desiredCapabilities.setCapability("deviceName", "xiaomi");
//        desiredCapabilities.setCapability("appium:platformVersion", "12.0.6");
//        desiredCapabilities.setCapability("appPackage", "com.hitachi.yunjia");
//        desiredCapabilities.setCapability("appActivity", "cn.com.hitachi.StartActivity");
//        desiredCapabilities.setCapability("noReset", true);
//        desiredCapabilities.setCapability("appium:ensureWebviewsHavePages", true);
//        desiredCapabilities.setCapability("appium:nativeWebScreenshot", true);
//        desiredCapabilities.setCapability("appium:connectHardwareKeyboard", true);
//        URL remoteUrl = new URL("http://127.0.0.1:4723/wd/hub");
//
//        AndroidDriver androidDriver = new AndroidDriver(remoteUrl, desiredCapabilities);
//        WebDriverWait wait = new WebDriverWait(androidDriver, 2);
//        wait.until(ExpectedConditions.presenceOfElementLocated(By.id(bo.getElementId())));
//        String text = androidDriver.findElement(By.id("com.hitachi.yunjia:id/tv_status")).getText();
//        if("离线".equals(text)){
//            throw new ServiceException("设备离线, 请检查设备状态");
//        }
//        androidDriver.findElement(By.id(bo.getElementId())).click();
        // 调用python exe 文件
        String exePath = bo.getElementId();

//        JsExecuteBo jsExecuteBo =  new JsExecuteBo();
//        jsExecuteBo.setExampleId(bo.getId());
//        jsExecuteService.insertByBo(jsExecuteBo);
        ProcessBuilder pb = new ProcessBuilder(exePath, "D:\\appuim\\dist\\OnOff.exe");
        //ProcessBuilder pb = new ProcessBuilder("python.exe","D:\\appuim\\script\\OnOff.py", jsExecuteBo.getId().toString());
        // 使用Runtime执行exe程序
        Process process =  pb.start();
//        // 获取执行结果
//        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
//        String line;
//        while ((line = reader.readLine()) != null) {
//            System.out.println(line);
//        }
//        reader.close();
//        // 等待进程结束
//        try {
//            int exitValue = process.waitFor();
//            if (exitValue == 0) {
//                System.out.println("执行成功");
//            } else {
//                throw new ServiceException("执行失败, 请检查设备状态");
//            }
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        return R.ok("执行成功");
    }

    /**
     * 导出测试用例列表
     */
    @SaCheckPermission("demo:example:export")
    @Log(title = "测试用例", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(JsExampleBo bo, HttpServletResponse response) {
        List<JsExampleVo> list = jsExampleService.queryList(bo);
        ExcelUtil.exportExcel(list, "测试用例", JsExampleVo.class, response);
    }

    /**
     * 获取测试用例详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("demo:example:query")
    @GetMapping("/{id}")
    public R<JsExampleVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(jsExampleService.queryById(id));
    }

    /**
     * 新增测试用例
     */
    @SaCheckPermission("demo:example:add")
    @Log(title = "测试用例", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody JsExampleBo bo) {
        return toAjax(jsExampleService.insertByBo(bo));
    }

    /**
     * 修改测试用例
     */
    @SaCheckPermission("demo:example:edit")
    @Log(title = "测试用例", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody JsExampleBo bo) {
        return toAjax(jsExampleService.updateByBo(bo));
    }

    /**
     * 删除测试用例
     *
     * @param ids 主键串
     */
    @SaCheckPermission("demo:example:remove")
    @Log(title = "测试用例", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(jsExampleService.deleteWithValidByIds(List.of(ids), true));
    }

}
